package com.ithong.drug.controller;

import com.ithong.drug.utils.ResultMapUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户相关的
 */
@Controller
public class UserController {

    /**
     * 登录界面
     * @return
     */
    @RequestMapping("login")
    public String login(){
        return "/login";
    }

    /**
     * 判断用户登录是否成功
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("toLogin")
    @ResponseBody
    public Object toLogin(String username,String password){
        if (username==null||password==null){
            return ResultMapUtil.getMapLogin("用户名密码不能为空","2");
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (UnknownAccountException e) {
            return ResultMapUtil.getMapLogin("用户名不存在","2");
        }catch (IncorrectCredentialsException e) {
            return ResultMapUtil.getMapLogin("密码错误","2");
        }
        return ResultMapUtil.getMapLogin("验证成功","1");
    }

    /**
     * 登录界面
     * @return
     */
    @RequestMapping("index")
    public String index(){
        return "/index";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

}
